//
//  GYHomeViewController.m
//  GoodLuck
//
//  Created by apple on 2018/1/26.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYHomeViewController.h"
#import "GYSectionHeadView.h"
#import "GYShopCell.h"
#import "GYShopHomeViewController.h"
#import "GYGoods.h"
#import <SDWebImage/SDWebImageManager.h>
#import "GYShopFirstCollectionViewCell.h"
#import "GYSearchViewController.h"
#import "GYSystemMessageViewController.h"
#import "GYUser.h"
#import "GYWebViewViewController.h"
#import "GYSearchResultViewController.h"
#import "GYHome.h"
#import "GYNewGoodsCollectionViewCell.h"
#import "GYBanner.h"
#import "ZXCycleScrollView.h"
#import "GYSpecialViewController.h"
#import "GYNetWorkTools.h"
#import "GYAppVersionView.h"
#import "GYTimeView.h"

static NSString *newGoodsCellIdentifier = @"newGoodsCellIdentifier";
static NSString *headViewIdentifier = @"headViewIdentifier";
static NSString *shopCellIdentifier = @"shopCellIdentifier";
static NSString *sectionFirstHeadView = @"sectionFirstHeadView";
static NSString *homeDataFileName = @"homeDataFileName.plist";

@interface GYHomeViewController ()<UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,ZXCycleScrollViewDelegate>

/** 展示视图 */
@property (nonatomic, weak) UICollectionView *collectionView;

/** cell缓存*/
@property (nonatomic, strong) NSMutableDictionary *cachesHeight;

/** 滑动视图 */
@property (nonatomic, strong) ZXCycleScrollView *scrollView;

/** 首页数据模型 */
@property (nonatomic, strong) GYHome *homeModel;

/** <#description#> */
@property (nonatomic, strong) UIView *appVersionView;

@end

@implementation GYHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化
    [self setupUI];
}

- (void)setupUI {
    self.navigationItem.title = @"有味生活";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"search_ico" tagret:self action:@selector(searchBtuClick) button:nil];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"message_b" tagret:self action:@selector(messageBtuClick) button:nil];
    
    //加载版本更新
    [self setupAppVersionView];
    
    //初始化collectionView
    [self setupCollectionView];
    
    //初始化首页数据
    [self setupHomeData];
}

- (void)searchBtuClick {
    //跳转到搜索界面
    GYSearchViewController *searchVC = [[GYSearchViewController alloc] init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)setupCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth, ScreenHeight-(iPhoneX ? 88 : 64)) collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource  = self;
    collectionView.backgroundColor = [UIColor whiteColor];//RGBColor(240, 240, 240);
    
    collectionView.contentInset = UIEdgeInsetsMake(0, 0, 10, 0);
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    //注册cell
    [collectionView registerNib:[UINib nibWithNibName:@"GYNewGoodsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:newGoodsCellIdentifier];
    [collectionView registerClass:[GYShopCell class] forCellWithReuseIdentifier:shopCellIdentifier];

    [collectionView registerNib:[UINib nibWithNibName:@"GYSectionHeadView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headViewIdentifier];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:sectionFirstHeadView];
    
    //下拉刷新
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupHomeData)];
    
}

- (void)setupHomeData {
    [GYHome loadHomeData:^(GYHome * _Nullable model, NSError * _Nullable error) {
        [self.collectionView.mj_header endRefreshing];
        if (model != nil) {
            //1.刷新数据
            self.homeModel = model;
            [self.collectionView reloadData];
            
        }else {
            //加载缓存数据
            [GYHome loadCachesHomeData:^(GYHome * _Nullable model) {
                if (model != nil) {
                    self.homeModel = model;
                    [self.collectionView reloadData];
                }
            }];
        }
    }];
}

- (void)setupAppVersionView {
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [GYNetWorkTools requestAppVesion:^(NSDictionary *obj) {
        //NSLog(@"obj=======%@",obj);
        int code = [[obj objectForKey:@"code"] intValue];
        NSDictionary *datas = [obj objectForKey:@"datas"];
        if (code == 200) {
            if ([datas isKindOfClass:[NSDictionary class]]) {
                NSString *version = [datas objectForKey:@"version"];
                if (![version isEqualToString:currentVersion]) {
                    NSArray *content = [datas objectForKey:@"content"];
                    UIView *bgViw = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                    bgViw.backgroundColor = [UIColor colorWithWhite:0.6 alpha:0.6];
                    //弹出更先进界面的提示
                    GYAppVersionView *appVersionView = [[[NSBundle mainBundle] loadNibNamed:@"GYAppVersionView" owner:nil options:nil] firstObject];
                    __weak typeof(self) weakSelf = self;
                    appVersionView.appUpdateCallBack = ^() {
                        //打开APP的下载地址
                        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/cn/app/jie-zou-da-shi/id1384768760?mt=8"]];
                        [weakSelf.appVersionView removeFromSuperview];
                    };
                    CGFloat height = [appVersionView getHeight:content];
                    appVersionView.frame = CGRectMake(50,ScreenHeight/2-height/2, ScreenWidth-100, height);
                    [bgViw addSubview:appVersionView];
                    
                    [[[UIApplication sharedApplication] keyWindow] addSubview:bgViw];
                    self.appVersionView = bgViw;
                }
            }
        }
    } error:^(NSError *error) {
        NSLog(@"error ====== %@",error);
    }];
}

#pragma mark -- 导航栏点击事件
- (void)messageBtuClick {
    //这里判断用户有没有登入 如果登陆了 则查看消息   没有登入则跳转到登入界面
    if ([GYUser loadUserInfo] == nil) {
        self.tabBarController.selectedIndex = 2;
        [self.tabBarController.tabBar setHidden:YES];
    }else {
        GYSystemMessageViewController *systemMsgVC = [[GYSystemMessageViewController alloc] initWithNibName:@"GYSystemMessageViewController" bundle:nil];
        systemMsgVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:systemMsgVC animated:YES];
    }
}

- (void)judgeType:(NSString *)type data:(NSString *)data {
    if ([type isEqualToString:@"keyword"]) {
        GYSearchResultViewController *searchResultVC = [[GYSearchResultViewController alloc] init];
        searchResultVC.currentSearchTitle = data;
        searchResultVC.hidesBottomBarWhenPushed = YES;
        
        [self.navigationController pushViewController:searchResultVC animated:YES];
    }else if ([type isEqualToString:@"special"]) {
        GYSpecialViewController *specialVC = [[GYSpecialViewController alloc] initWithNibName:@"GYSpecialViewController" bundle:nil];
        specialVC.special_id = data;
        specialVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:specialVC animated:YES];
        
    }else if ([type isEqualToString:@"goods"]) {
        GYShopHomeViewController *shopController = [[GYShopHomeViewController alloc] init];
        shopController.hidesBottomBarWhenPushed = YES;
        shopController.goods_id = data;
        [self.navigationController pushViewController:shopController animated:YES];
    }else if ([type isEqualToString:@"url"]) {
        GYWebViewViewController *webViewVC = [[GYWebViewViewController alloc] initWithNibName:@"GYWebViewViewController" bundle:nil];
        webViewVC.url = [NSURL URLWithString:data];
        webViewVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webViewVC animated:YES];
    }else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"该商品正在上线,敬请期待!" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

#pragma mark -- UICollectionViewDataSource and UICollectionViewDelegate and UICollectionViewDelegateFlowLayout

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return section == 0 ? self.homeModel.home_news.count : self.homeModel.home_Goods.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        GYNewGoodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:newGoodsCellIdentifier forIndexPath:indexPath];
        cell.model = self.homeModel.home_news[indexPath.item];
        
        return cell;
    }else {
        GYShopCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:shopCellIdentifier forIndexPath:indexPath];
        cell.goods = self.homeModel.home_Goods[indexPath.item];
        
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        GYNewGoods *model = self.homeModel.home_news[indexPath.item];
        [self judgeType:model.type data:model.data];
    }else {
        GYShopHomeViewController *shopController = [[GYShopHomeViewController alloc] init];
        shopController.hidesBottomBarWhenPushed = YES;
        GYGoods *goods = self.homeModel.home_Goods[indexPath.item];
        shopController.goods_id = goods.goods_id;
        [self.navigationController pushViewController:shopController animated:YES];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        if (indexPath.section == 0) {
            UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:sectionFirstHeadView forIndexPath:indexPath];
            
            //1.添加子控件
            NSMutableArray *urls = [NSMutableArray array];
            for (int i = 0; i<self.homeModel.home_banners.count; i++) {
                GYBanner *banner = self.homeModel.home_banners[i];
                [urls addObject:banner.image];
            }
            if (self.scrollView == nil) {
                ZXCycleScrollView *scrollView = [ZXCycleScrollView  initWithFrame:CGRectMake(0,[GYAutoScale heightScale:10 originalSize:iphone6_H], ScreenWidth, [GYAutoScale heightScale:350 originalSize:iphone6_H]) withMargnPadding:20 withImgWidth:[GYAutoScale widthScale:260 originalSize:iphone6_W] dataArray:urls] ;
                scrollView.delegate = self;
                [self.view addSubview:scrollView];
                scrollView.autoScroll = YES;
                scrollView.autoScrollTimeInterval = 5.0;
                
                [headView addSubview:scrollView];
                self.scrollView = scrollView;
                
                UILabel *bglable = [[UILabel alloc] initWithFrame:CGRectMake(10, scrollView.height+[GYAutoScale heightScale:29 originalSize:iphone6_H], ScreenWidth-20, 2)];
                bglable.backgroundColor = RGBColor(216, 216, 216);
                
                [headView addSubview:bglable];
                
                //添加标题
                UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, bglable.y+2+[GYAutoScale heightScale:19 originalSize:iphone6_H], 200, 40)];
                titleLable.text = @"RELISH LIFE";
                titleLable.font = [UIFont systemFontOfSize:24];
                [headView addSubview:titleLable];
                
                GYTimeView *timeView = [[[NSBundle mainBundle] loadNibNamed:@"GYTimeView" owner:nil options:nil] firstObject];
                timeView.frame = CGRectMake(ScreenWidth-120, titleLable.y, 100, 40);
                [headView addSubview:timeView];
                
            }else {
                self.scrollView.sourceDataArr = urls;
                self.scrollView.showPageControl = YES;
                self.scrollView.curPageControlColor = RGBColor(0, 158, 214);
                self.scrollView.otherPageControlColor = [UIColor grayColor];
            }
            
            return headView;
            
        }else {
            
            GYSectionHeadView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headViewIdentifier forIndexPath:indexPath];
            headView.sectionTitleLable.text = self.homeModel.goodsSectionTitle;
            
            return headView;
        }
    }
    return nil;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 10, 0, 10);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return section == 0 ? CGSizeMake(ScreenWidth, [GYAutoScale heightScale:400 originalSize:iphone6_H]+40) : CGSizeMake(ScreenWidth, 80);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        GYNewGoods *model = self.homeModel.home_news[indexPath.item];
        return CGSizeMake(ScreenWidth-20, [model height]);
    }else {
        
//        CGFloat height = CGFLOAT_MIN;
//        for (GYGoods *model in self.homeModel.home_Goods) {
//            CGFloat rowHeight = [model getHeight];
//            if (rowHeight > height) {
//                height = rowHeight;
//            }
//        }
//
//        return CGSizeMake((ScreenWidth-30)/2, height);
        GYGoods *goods = self.homeModel.home_Goods[indexPath.item];

        //1.首选从缓存中取
        CGFloat height = [self.cachesHeight[goods.goods_id] floatValue];
        if (height != 0) {
            return CGSizeMake((ScreenWidth-30)/2, height);
        }

        //没有高度
        CGFloat rowHeight = [goods getHeight];
        [self.cachesHeight setObject:@(rowHeight) forKey:goods.goods_id];
        return CGSizeMake((ScreenWidth-30)/2, [goods getHeight]);
    }
}

#pragma mark -- ZXCycleScrollViewDelegate
-(void)zxCycleScrollView:(ZXCycleScrollView *)scrollView didScrollToIndex:(NSInteger)index {
    //NSLog(@"index------%lu",index);
}

-(void)zxCycleScrollView:(ZXCycleScrollView *)scrollView didSelectItemAtIndex:(NSInteger)index {
    //NSLog(@"点击了----index------%lu",index);
    GYBanner *banner = self.homeModel.home_banners[index];
    [self judgeType:banner.type data:banner.data];
}










#pragma mark -- 懒加载

- (NSMutableDictionary *)cachesHeight {
    if (!_cachesHeight) {
        _cachesHeight = [NSMutableDictionary dictionary];
    }
    
    return _cachesHeight;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    self.cachesHeight = nil;
}
@end



